<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>工具集</title>

    <style type="text/css">
        .btn {
            color: #fff;
            background-color: #286090;
            border-color: #204d74;
            width: 70px;
            height: 30px;
        }

        .type {
            width: 200px;
            height: 30px;
        }

        /* 提示 */
        .notification {
            position: fixed;
            width: 100px;
            top: 5%;
            left: 50%;
            padding: 15px;
            background-color: #f0f0f0;
            color: #333;
            border: 1px solid #ccc;
            border-radius: 5px;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
            z-index: 9999;
            opacity: 1;
            transition: opacity 0.3s ease-in-out;
            text-align: center;
        }

        .notification:hover {
            opacity: 0.8;
        }
    </style>
</head>

<body>
    <script>
    	function tr0() {
    		try {
    			tr();
    		} catch (error) {
    			console.error('error:', error.message, error);
    			alert(error.message);
			}
    	}

        function tr() {
            var a = document.getElementById("input").value;
            // console.log(a);

            var b;

            var type = document.getElementById("type").value;
            switch (type) {
                case 'base64E':
                    b = base64E(a);
                    break;
                case 'base64D':
                    b = base64D(a);
                    break;
                case 'urlE':
                    b = encodeURIComponent(a);
                    break;
                case 'urlD':
                    b = decodeURIComponent(a);
                    break;
                case 'str216':
                	b = str216(a);
                	break;
                case 'hexToStr':
                	b = hexToStr(a);
                	break;
                case 'json1':
                	b = parsejson(a);
                	break;
                case 'json2':
                	b = JSON.stringify(a);
                	break;
                case 'toSqlIn':
                	b = toSqlIn(a);
                break;
				case 'toSort': b = toSort(a);break;
                default:
                    alert("不支持");
            }

            document.getElementById("output").value = b;

            copyToClip(b);
        }

		/**
		* 字符串回车符分割为数组，去除内部空字符串
		**/
		function getArray(str) {
			const lines = str.split('\n');

			return lines.filter(item => item !== '');
		}

		function toSort(str) {
			const lines = getArray(str);

			lines.sort();

			return lines.join('\n');
		}

        function parsejson(a) {
			if (a.charAt(0) != '"') {
        		a = "\"" + a;
        	}
        	if (a.charAt(a.length-1) != '"') {
        		a = a + "\"";
        	}

        	console.log(a);

        	return JSON.parse(a);
        }

        function base64E(content) {
            return window.btoa(unescape(encodeURIComponent(content)));
        }
        function base64D(content) {
            return decodeURIComponent(escape(window.atob(content)));
        }

        function copy() {
            var a = document.getElementById("output").value;
            
            copyToClip(a);
        }

        /**
 * 复制多行内容到粘贴板
 * contentArray: 需要复制的内容（传一个字符串数组）
 * message : 复制完后的提示，不传则默认提示"复制成功"
 */
        function copyToClip(contents, message) {
            if (contents == null || contents === '') {
                return;
            }

            const textarea = document.createElement('textarea');
            textarea.value = contents;
            document.body.appendChild(textarea);
            textarea.select();
            if (document.execCommand('copy')) {
                document.execCommand('copy');
            }
            document.body.removeChild(textarea);
            if (message == null) {
                showNotification("复制成功", 1000);
            } else {
                showNotification(message);
            }
        }

        //提示信息
        function showNotification(message, duration) {
            var notification = document.createElement('div');
            notification.className = 'notification';
            notification.textContent = message;
            document.body.appendChild(notification);
            setTimeout(function () {
                notification.style.opacity = 0;
                setTimeout(function () {
                    document.body.removeChild(notification);
                }, 1000);
            }, duration);
        }

        function str216(str) {
			let hex = ''; // 初始化hex变量
		    const encoder = new TextEncoder();
		    const uint8array = encoder.encode(str);
		    for (let i = 0; i < uint8array.length; i++) {
		        hex += uint8array[i].toString(16).padStart(2, '0');
		    }
		    return hex;
		}

		function hexToStr(hex) {
			// 确保输入是16进制字符串
		    if (hex.length % 2 !== 0) {
		        throw new Error('Invalid hex string');
		    }

		    // 创建一个Uint8Array来存储字节
		    const bytes = new Uint8Array(hex.length / 2);
		    for (let i = 0; i < hex.length; i += 2) {
		        bytes[i / 2] = parseInt(hex.substr(i, 2), 16);
		    }

		    // 使用TextDecoder解码UTF-8字节序列
		    const decoder = new TextDecoder('utf-8');
		    return decoder.decode(bytes);
		}

		function jsonFormat() {
			var a = document.getElementById("json_input").value;
            console.log(a);

            var j = JSON.parse(a);
            console.log(j);

            const b = JSON.stringify(j, null, 2);

			console.log(b);

            document.getElementById("json_input").value = b;
		}

		function toSqlIn(inputValue) {
			// 获取输入框的值并按回车符分割
            const lines = getArray(inputValue);

            // 在每个字符串两端加上英文单引号
            const quotedLines = lines.map(line => `'${line.trim()}'`);

            // 用逗号连接成一个字符串
            const finalString = quotedLines.join(', ');

            // 显示结果
            return finalString;
		}
    </script>

    <!-- 转换 -->
    <div>
        <label for="name">输入：</label>
        <textarea id="input" rows="10" cols="30"></textarea>
        <select id="type" class="type" onchange="tr0()">
            <option value="base64E">base64编码</option>
            <option value="base64D">base64解码</option>
            <option value="urlE">url编码</option>
            <option value="urlD">url解码</option>
            <option value="str216">字符串转16进制</option>
            <option value="hexToStr">16进制转字符串</option>
            <option value="json1">json去除转义</option>
            <option value="json2">json转义</option>
            <option value="toSqlIn">回车符分隔为sqlIn字符串</option>
			<option value="toSort">字符串排序</option>
        </select>
        <button onclick="tr0()" class="btn">转换</button>
        <textarea id="output" rows="10" cols="30"></textarea>
        <button onclick="copy()" class="btn">复制</button>
    </div>
    <hr>
    <label>json工具:</label>
    <textarea id="json_input" rows="20" style="width: 50%"></textarea>
    <button onclick="jsonFormat()" class="btn">格式化</button>
</body>

</html>